package com.xb.sourest.api;
import android.util.Log;

import com.xb.sourest.BuildConfig;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;

/**
 * 网络封装
 */
public  class ApiClent {


    private  ApiService mApiService;

    private static ApiClent  mApicLient;

    public  static  ApiClent getInstance(){
        if (mApicLient ==null){
            mApicLient = new ApiClent();
        }
        return  mApicLient;
    }


    private ApiClent (){
        initOkhttp();
    }

    private void initOkhttp() {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new  HttpLoggingInterceptor().setLevel(BuildConfig.IS_DEBUG ?
                        HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE))
                .addNetworkInterceptor(new NetInterceptor())
                .retryOnConnectionFailure(false)
                .readTimeout(15, TimeUnit.SECONDS) // 设置读取超时
                .connectTimeout(15, TimeUnit.SECONDS) // 设置连接超时
                //适配android9.0 https请求需要证书
                .sslSocketFactory(Https.getSslSocketFactory(null, null, null).sSLSocketFactory)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }).build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl(BuildConfig.POST_URL)
                .addConverterFactory(GsonConverterFactory.create()) // 设置请求格式化为Json类型
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 设置Retrofit请求返回的是Observable对象
                .client(okHttpClient) // 设置Retrofit使用的OkHttp的对象
                .build();// 创建Retrofit对象

        mApiService = retrofit.create(ApiService.class);

    }


    public  ApiService getApiService(){
        return  mApiService;
    }





    private  class  NetInterceptor  implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            //添加共同参数
            Request  request = chain.request().newBuilder().addHeader("token", "")
                    .addHeader("clientType", "Android").build();

            //是否打印日志
            if (BuildConfig.IS_DEBUG){
              RequestBody requestBody  =  chain.request().body();
              if (requestBody != null){
                  MediaType mediaType = requestBody.contentType();
                  if (mediaType != null){
                        if (isText(mediaType)){
                            Log.e("unfind","url:"+chain.request().toString()+ "   params : " + bodyToString(request));
                        }else {
                            Log.e("unfind", "params : " + " maybe [file part] , too large too print , ignored!");
                        }
                  }

              }
            }
            return chain.proceed(request);
        }
    }

    private boolean isText(MediaType mediaType) {
        return mediaType == null ? false : ("text" == mediaType.subtype()
                || "json" == mediaType.subtype()
                || "xml" == mediaType.subtype()
                || "html" == mediaType.subtype()
                || "webviewhtml" == mediaType.subtype()
                || "x-www-form-urlencoded" == mediaType.subtype());

    }

    /*************打印请求数据********************/
    private String bodyToString(Request  request) {
        try {
            Request build = request.newBuilder().build();
            Buffer buffer = new Buffer();
            build.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (IOException en) {
            return "something error when show requestBody.";
        }

    }

}
